//
//  HistoryViewController.swift
//  TestProject
//
//  Created by 万想想 on 2020/8/19.
//  Copyright © 2020 edaili. All rights reserved.
//


import Foundation
import Moya
import Alamofire
import SwiftyJSON


// 超时时长
private var requestTimeOut: Double = 30
//成功数据的回调
typealias SuccessCallback = ((String) -> (Void))
//失败的回调
typealias FailedCallback = ((String) -> (Void))
//网络错误的回调
typealias ErrorCallback = (() -> (Void))

struct NetworkErrorDescription {
    static let network = "网络不给力，请检查网络设置"
    static let server  = "网络请求失败，请稍后再试"
    static let parser  = "网络请求异常"
}

enum NetworkErrorType {
    case networkError  // 无网络连接
    case serverError   // 服务异常,非200
    case parserError   // 数据解析错误
    case othersError(description: String)   // 服务器返回的错误描述
    
    var descriptions: String {
        switch self {
        case .networkError:
            return NetworkErrorDescription.network
        case .serverError:
            return NetworkErrorDescription.server
        case .parserError:
            return NetworkErrorDescription.parser
        case .othersError(let description):
            return description
        }
    }
}
// MARK: -- 网络请求的基本设置,这里可以拿到是具体的哪个网络请求，可以在这里做一些设置
private let MyEndpointClosure = { (target: API) -> Endpoint in
    var url = target.path
    
    let task:Task = target.task
    
    var endpoint = Endpoint (
        url: url,
        sampleResponseClosure: { .networkResponse(200, target.sampleData) },
        method: target.method,
        task: target.task,
        httpHeaderFields: target.headers
    )
    
    requestTimeOut = 30
    return endpoint
    
}

// MARK: -- 网络请求的设置
private let requestClosure = { (endpoint: Endpoint, done: MoyaProvider.RequestResultClosure) in
    do{
        var request:URLRequest = try endpoint.urlRequest()
        // 设置请求时长
        request.timeoutInterval = requestTimeOut
        done(.success(request))
        
    }catch{
        done(.failure(MoyaError.underlying(error, nil)))
    }
}

// MARK: -- NetworkActivityPlugin插件用来监听网络请求，界面上做相应的展示
private let networkPlugin = NetworkActivityPlugin.init { (changeType, targetType) in
    
}

// MARK: -- 网络请求发送的核心初始化方法，创建网络请求对象
let Provider = MoyaProvider<API>(endpointClosure: MyEndpointClosure, requestClosure: requestClosure, plugins: [networkPlugin], trackInflights: false)

// MARK: -- 最常用的网络请求，只需知道正确的结果无需其他操作时候用这个
func NetWorkRequest(_ target: API, completion: @escaping SuccessCallback ){
    NetWorkRequest(target, completion: completion, failed: nil, errorResult: nil)
}
// MARK: -- 需要知道成功或者失败的网络请求， 要知道code码为其他情况时候用这个
func NetWorkRequest(_ target: API, completion: @escaping SuccessCallback , failed:FailedCallback?) {
    NetWorkRequest(target, completion: completion, failed: failed, errorResult: nil)
}
// MARK: -- 需要知道成功、失败、错误情况回调的网络请求   像结束下拉刷新各种情况都要判断
func NetWorkRequest(_ target: API, completion: @escaping SuccessCallback, failed:FailedCallback? , errorResult: ErrorCallback?) {
    if !Tool.isNetworkConnect() {
        switch target{
        default:
            if failed != nil{
                failed!("您的网络似乎出现了问题")
            }
        }
        return
    }
    Provider.request(target) { (result) in
        switch result {
        case let .success(response):
            do{
                //这里转JSON用的swiftyJSON框架
                let jsonData = try JSON(data: response.data)
                if jsonData[RESPONSE_CODE].stringValue == ResponseCode.success {
                    print("返回参数"+"\(jsonData)")
                    completion(String(data: response.data, encoding: String.Encoding.utf8)!)
                }else{
                    if failed != nil{
                        failed!(String(jsonData[RESPONSE_MESSAGE].stringValue))
                    }
                }
                
            }catch{
                let code = response.statusCode
                print("网络异常:\(code)")
                if failed != nil{
                    failed!("网络异常:\(code)")
                }
            }
        case let .failure(errss):
//            EdlToast.hiddenToastActionForView()
//            EdlToast.showToast(message: errss.localizedDescription)
            print(errss)
            if failed != nil {
                failed!("网络异常")
            }
        }
    }
    
}
